package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Paint
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.flowlayout.FlowLayout
import com.gexiaobao.flowlayout.TagAdapter
import com.gexiaobao.flowlayout.TagFlowLayout
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.GoodsDetailCouponListResponse
import com.gexiaobao.pigeon.app.model.bean.GoodsDetailResponse
import com.gexiaobao.pigeon.app.model.bean.GoodsSkuResponse
import com.gexiaobao.pigeon.app.model.bean.ShopServiceListResponse
import com.gexiaobao.pigeon.app.model.param.AddShoppingCarParam
import com.gexiaobao.pigeon.app.model.param.BuyNowParam
import com.gexiaobao.pigeon.app.model.param.CollectParam
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.util.WxShareUtils
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentProductDetailBinding
import com.gexiaobao.pigeon.ui.activity.TestInputActivity
import com.gexiaobao.pigeon.ui.adapter.CouponAdapter
import com.gexiaobao.pigeon.ui.adapter.DetailCouponListAdapter
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.adapter.ProductEvaluateAdapter
import com.gexiaobao.pigeon.ui.adapter.ProductIntroduceAdapter
import com.gexiaobao.pigeon.ui.adapter.ProductIntroduceImageAdapter
import com.gexiaobao.pigeon.ui.adapter.ServiceListAdapter
import com.gexiaobao.pigeon.ui.adapter.ShopServiceAdapter
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.luck.picture.lib.thread.PictureThreadUtils
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONException
import org.json.JSONObject
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.Date

/**
 * @Author      : hxw
 * @Date        : 2024/3/8 8:48
 * @Describe    :
 */
class FragmentStoreGoodsDetail : BaseFragment<MallViewModel, FragmentProductDetailBinding>() {

    private var goodsUnitPrice: Double = 0.00
    private var goodsTotalPrice: Double = 0.00
    private var shopId: Int = 0
    private var isCollect: Boolean = false
    private var ivSkuLogo: ImageView? = null
    private var skuList: ArrayList<GoodsSkuResponse.ListBean> = arrayListOf()
    private var mGoodsId = ""
    private var specId = -1
    private var buyCount = 1
    var checkPosition = -1
    private var brandLogo = ""
    private var buyType = 0
    private val mAdapter: ProductIntroduceAdapter by lazy { ProductIntroduceAdapter(arrayListOf()) }
    private val mAdapterImage: ProductIntroduceImageAdapter by lazy { ProductIntroduceImageAdapter(arrayListOf()) }
    private val mAdapterEvaluate: ProductEvaluateAdapter by lazy { ProductEvaluateAdapter(arrayListOf()) }
    private val mAdapterCoupon: CouponAdapter by lazy { CouponAdapter(arrayListOf()) }
    private lateinit var detailResult: GoodsDetailResponse
    private lateinit var goodsSkuResult: GoodsSkuResponse
    private lateinit var dialogBottom: BottomSheetDialog
    private lateinit var dialogBottomCoupon: BottomSheetDialog
    private lateinit var btnSubmit: Button
    private lateinit var buySkuNoLl: LinearLayout
    private lateinit var buySkuAdd: AppCompatTextView
    private lateinit var buySkuRe: AppCompatTextView
    private lateinit var ibSkuClose: ImageView
    private lateinit var buySkuNo: TextView
    private lateinit var tvSkuSellingPrice: TextView
    private lateinit var tvSkuSellingPriceUnit: TextView
    private lateinit var tvSkuInfo: TextView
    private lateinit var llCoupon: LinearLayout
    private var isHaveAddress = false//判断是有收货地址
    private var couponShopId = 0
    private var couponListData: ArrayList<GoodsDetailCouponListResponse.ListBean> = arrayListOf()
    private var lowPriceSpecIndex: Int = -1//默认选中的商品规格的小标
    private val mAdapterShopService: ShopServiceAdapter by lazy { ShopServiceAdapter(arrayListOf()) }
    private lateinit var mShopServiceList: ShopServiceListResponse
    private var addressId = 0
    private var bannerImgList: ArrayList<String> = arrayListOf()
    private var channelId = ""

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun onResume() {
        super.onResume()
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
        initData()
    }

    @RequiresApi(Build.VERSION_CODES.M)
    @SuppressLint("ResourceAsColor", "MissingInflatedId", "SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeContent.includeContentOne.viewmodel = mViewModel
        mDatabind.includeContent.includePriceInfo.tvPriceShow.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        mGoodsId = requireArguments().getString("id").toString()

        /** 初始化商品服务列表recycleView */
        mDatabind.includeContent.includeContentOne.recyclerviewShopServices.init(GridLayoutManager(context, 2), mAdapterShopService)
            .addItemDecoration(
                SpaceItemDecoration(0, Util.dp2px(context, 5f))
            )
        /** 初始化产品介绍recycleView */
        mDatabind.includeContent.includeContentTwo.recyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 5f))
        )
        mDatabind.includeContent.includeContentTwo.recyclerView.adapter = mAdapter
        /** 初始化底部图片recycleView */
        mDatabind.includeContent.includeContentTwo.recyclerViewImage.init(LinearLayoutManager(context), mAdapterImage).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 0f))
        )
        mDatabind.includeContent.includeContentTwo.recyclerViewImage.adapter = mAdapterImage
        /** 初始化底部图片recycleView */
        mDatabind.includeContent.includeContentTwo.recyclerEvaluate.init(LinearLayoutManager(context), mAdapterEvaluate).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 5f))
        )
        mDatabind.includeContent.includeContentTwo.recyclerEvaluate.adapter = mAdapterEvaluate
        /** 给adapter添加尾部 查看全部评价按钮 */
        val footerView = LayoutInflater.from(context).inflate(R.layout.view_evaluate_footer, null)
        footerView.setPadding(0, 30, 0, 0)
        mAdapterEvaluate.addFooterView(footerView)
        footerView.findViewById<AppCompatTextView>(R.id.tvLookAllEvaluate).setOnClickListener {
            nav().navigateAction(R.id.action_to_fragment_view_comments, Bundle().apply {
                putInt("goodId", id.toInt())
            })
        }
        mDatabind.swipeRefreshGoodsDetail.init {
            showLoadingAntiShake(getString(R.string.loading))
            mViewModel.getGoodDetail(mGoodsId)
//            mViewModel.getAddressList()
        }
        /** 初始化优惠券列表 */
        mDatabind.includeContent.includeContentTwo.swipeRecyclerViewCoupon.init(
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false),
            mAdapterCoupon
        )
            .addItemDecoration(
                SpaceItemDecoration(Util.dp2px(context, 10f), Util.dp2px(context, 0f))
            )
        mDatabind.includeContent.includeContentTwo.swipeRecyclerViewCoupon.adapter = mAdapterCoupon

        mDatabind.includeToolbar.toolBarProductDetail.background.alpha = 0
        mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.TRANSPARENT)
        mDatabind.includeContent.nestedScrollView.setOnScrollChangeListener { _, _, scrollY, _, _ ->
            val toolbarHeight = mDatabind.includeToolbar.toolBarProductDetail.bottom * 1.5f
            if (scrollY <= toolbarHeight) {
                val scale = scrollY.toFloat() / toolbarHeight
                val alpha = scale * 255
                mDatabind.includeToolbar.toolBarProductDetail.setBackgroundColor(Color.argb(alpha.toInt(), 254, 69, 66))
                mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.argb(alpha.toInt(), 255, 255, 255))
            } else {
                mDatabind.includeToolbar.toolBarProductDetail.setBackgroundColor(ContextCompat.getColor(requireContext(), R.color.color_fe4542))
                mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.WHITE)
            }
        }
        mAdapterShopService.setOnItemClickListener { _, _, _ ->
            showBottomServiceDialog()
        }
    }

    override fun initData() {
        val addressData = CacheUtil.getAddressInfo()
        if (addressData != null) {
            isHaveAddress = true
            addressId = addressData.id
            mDatabind.includeContent.includeContentTwo.tvReceiveAddress.text = addressData.address
            mDatabind.includeContent.includeContentTwo.tvDetailReceiveAddress.text = addressData.detailedAddress
            mDatabind.includeContent.includeContentTwo.tvDetailReceiveAddress.isVisible = true
        } else {
            isHaveAddress = false
            addressId = 0
            mDatabind.includeContent.includeContentTwo.tvReceiveAddress.text = "您还没有收货地址"
            mDatabind.includeContent.includeContentTwo.tvChangeAddress.text = "去设置"
            mDatabind.includeContent.includeContentTwo.tvDetailReceiveAddress.isVisible = false
        }
    }

    private fun showBottomServiceDialog() {
        val mServiceListAdapter: ServiceListAdapter by lazy { ServiceListAdapter(arrayListOf()) }
        val dialogBottomService = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_service_list, null)
        val swipeRecyclerViewService = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerViewService)
        val ivServiceClose = dialogView.findViewById<AppCompatImageView>(R.id.ivServiceClose)

        swipeRecyclerViewService.init(LinearLayoutManager(context), mServiceListAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )
        swipeRecyclerViewService.adapter = mServiceListAdapter
        if (::mShopServiceList.isInitialized && mShopServiceList != null) {
            mServiceListAdapter.setList(mShopServiceList.list)
            mServiceListAdapter.notifyDataSetChanged()
        }

        ivServiceClose.setOnClickListener {
            dialogBottomService.dismiss()
        }

        dialogBottomService.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogBottomService.setContentView(dialogView)
        dialogBottomService.show()
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh()
    }

    private fun onRefresh() {
        showLoadingAntiShake(getString(R.string.loading))
        mViewModel.getGoodDetail(mGoodsId)
        mViewModel.getShopServiceList()
        mViewModel.getReviewsList(id.toInt(), 0)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBottom.addCar,
            mDatabind.includeBottom.buySure,
            mDatabind.includeBottom.llProductDetailShopCar,
            mDatabind.includeContent.includeContentTwo.tvGoodsDetailPositiveFeedback,
            mDatabind.includeContent.includeContentTwo.ivGoodsDetailPositiveFeedback,
            mDatabind.includeToolbar.ivBack,
            mDatabind.includeBottom.llProductDetailCollect,
            mDatabind.includeBottom.llProductDetailShop,
            mDatabind.includeContent.includeContentTwo.llDetailStoreInfo,
            mDatabind.includeContent.includeContentTwo.llChangeAddress,
            mDatabind.includeContent.includeContentTwo.ivDetailReceiveAddress,
            mDatabind.includeContent.includeContentOne.tvProductDetailRecharge,
            mDatabind.includeContent.includeContentTwo.tvProductSku,
            mDatabind.includeContent.includeContentTwo.ivProductSku,
            mDatabind.floatingActionButtonShopCar,
            mDatabind.includeContent.includeContentOne.ivShopServiceArrow,
            mDatabind.includeToolbar.ivShareGoodsDeail,
            mDatabind.includeBottom.llProductDetailShopService
        ) {
            when (it) {
                mDatabind.includeToolbar.ivBack -> {
                    nav().navigateUp()
                }

                mDatabind.includeContent.includeContentTwo.tvGoodsDetailPositiveFeedback, mDatabind.includeContent.includeContentTwo.ivGoodsDetailPositiveFeedback -> {
                    nav().navigateAction(R.id.action_to_fragment_view_comments, Bundle().apply {
                        putInt("goodId", id.toInt())
                    })
                }

                mDatabind.includeBottom.llProductDetailShopCar -> {
                    nav().navigateAction(R.id.action_to_fragment_shop_car)
                }

                mDatabind.floatingActionButtonShopCar -> {
                    nav().navigateAction(R.id.action_to_fragment_shop_car)
                }

                mDatabind.includeBottom.llProductDetailShop -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", shopId)
                    })
                }

                mDatabind.includeBottom.addCar -> {
                    buyType = 1
                    showBottomDialogAddCar(0)//0:加入购物车或立即购买
                }

                mDatabind.includeBottom.buySure -> {
                    buyType = 2
                    showBottomDialogAddCar(0)//0:加入购物车或立即购买
                }

                mDatabind.includeContent.includeContentTwo.llDetailStoreInfo -> {
                    nav().navigateAction(R.id.action_to_fragment_Store_info, Bundle().apply {
                        putInt("shopId", shopId)
                    })
                }

                mDatabind.includeContent.includeContentTwo.llChangeAddress -> {
                    if (isHaveAddress) {
                        nav().navigateAction(R.id.action_to_receive_address, Bundle().apply {
                            putInt("type", 1)
                        })
                    } else {
                        nav().navigateAction(R.id.action_to_add_receive_address, Bundle().apply {
                            putString("type", "")
                        })
                    }
                }

                mDatabind.includeBottom.llProductDetailCollect -> {
                    collectGoods()
                }

                mDatabind.includeContent.includeContentOne.tvProductDetailRecharge -> {
                    nav().navigateAction(R.id.action_to_account_recharge)
                }

                mDatabind.includeContent.includeContentTwo.tvProductSku, mDatabind.includeContent.includeContentTwo.ivProductSku -> {
                    showBottomDialogAddCar(1)
                }

                mDatabind.includeContent.includeContentOne.ivShopServiceArrow -> {
                    showBottomServiceDialog()
                }

                mDatabind.includeToolbar.ivShareGoodsDeail -> {
                    val url = "https://baidu.com"
                    LogUtils.debugInfo(url)
                    try {
                        val sdf = SimpleDateFormat("yyyy-MM-dd")
                        val dateFormatString = sdf.format(Date(System.currentTimeMillis()))
                        val bmp = BitmapFactory.decodeResource(resources, R.mipmap.app_icon_)
                        WxShareUtils.shareWeb(
                            context, Constant.WX_APP_ID,
                            url, "商品的描述", "" + dateFormatString,
                            bmp
                        )
                    } catch (e: Exception) {
                        e.printStackTrace()
                        LogUtils.debugInfo("获取比赛结果信息失败")
                    }
                }

                mDatabind.includeBottom.llProductDetailShopService -> {
                    chatLogin()
                }
            }
        }
    }

    private fun chatLogin() {
        val token = CacheUtil.getToken()
        val uid = KvUtils.decodeString(Constant.USERID)
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("uid", uid)
                jsonObject.put("token", token)
                jsonObject.put("device_flag", 0)
                jsonObject.put("device_level", 1)
            } catch (e: JSONException) {
                throw RuntimeException(e)
            }
            Thread {
                HttpUtil.getInstance().post("/user/token", jsonObject) { code, _ ->
                    if (code == 200) {
                        startActivity<TestInputActivity>("channelId" to channelId, "token" to token, "uid" to uid)
                    } else {
                        PictureThreadUtils.runOnUiThread {
                            RxToast.showToast("登录失败【$code】")
                        }
                    }
                }
            }.start()
        }
    }

    private fun collectGoods() {
        if (isCollect) {
            mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_unchecked)
        } else {
            mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_checked)
        }
        showLoadingAntiShake(getString(R.string.loading))
        val body = CollectParam(goodId = id.toInt())
        if (isCollect) {
            mViewModel.cancelCollectGood(body)
        } else {
            mViewModel.addCollectGood(body)
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 取商铺服务列表 */
        mViewModel.shopServiceListResult.observe(viewLifecycleOwner) {
            if (!it.isEmpty()) {
                mShopServiceList = it
                mAdapterShopService.setList(it.list)
                mAdapterShopService.notifyDataSetChanged()
            }
        }
        /** 添加收藏 */
        mViewModel.collectResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                isCollect = true
                RxToast.showToast("已收藏")
                mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_checked)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }

        /** 取消收藏 */
        mViewModel.cancelCollectResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            if (it.isSuccess) {
                isCollect = false
                RxToast.showToast("已取消收藏")
                mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_unchecked)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
        /** 获取评价列表  */
        mViewModel.viewCommentsResult.observe(viewLifecycleOwner) {
            if (!it.isEmpty()) {
                mDatabind.includeContent.includeContentTwo.tvProductDetailEvaTotal.text = "(" + it.list.size.toString().trim() + ")"
                mAdapterEvaluate.setList(it.list)
                mDatabind.includeContent.includeContentTwo.llNoEvaluate.visibility = View.GONE
                mDatabind.includeContent.includeContentTwo.llEvaluate.visibility = View.VISIBLE
            } else {
                mDatabind.includeContent.includeContentTwo.llNoEvaluate.visibility = View.VISIBLE
                mDatabind.includeContent.includeContentTwo.llEvaluate.visibility = View.GONE
            }
        }
        /** 立即购买  */
        mViewModel.buyNowResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            nav().navigateAction(R.id.action_to_fragment_order_detail, Bundle().apply {
                putString("orderId", it.orderId.toString())
                putString("type", "detail")
            })
            dialogBottom.dismiss()
        }
        /** 获取商品详情  */
        mViewModel.goodsDetailResult.observe(viewLifecycleOwner) {
            dismissLoadingFunction()
            setProductData(it)
            detailResult = it
            mViewModel.getGoodSkuList(mGoodsId)
        }
        /** 获取商品sku列表 */
        mViewModel.goodsSkuResult.observe(viewLifecycleOwner) {
            dismissLoading()
            setProductSkuData(it)
            goodsSkuResult = it
        }
        /** 添加到购物车  */
        mViewModel.addShoppingCarResult.observe(viewLifecycleOwner) {
            dismissLoadingAntiShake()
            eventViewModel.addShopCarResult.value = true
            RxToast.showToast("已添加")
            if (dialogBottom.isShowing)
                dialogBottom.dismiss()
        }
        /** 立即购买获取可使用的优惠券列表 */
        mViewModel.buyNowCouponSizeResult.observe(viewLifecycleOwner) {
            if (it != null) {
                if (!it.isEmpty()) {
                    couponListData.clear()
                    couponListData.addAll(it.list)
                }
            }
            if (!::dialogBottomCoupon.isInitialized || !dialogBottomCoupon.isShowing) {
                showBottomCouponDialog(it)
            }
        }
    }

    private fun dismissLoadingFunction() {
        dismissLoadingAntiShake()
        if (mDatabind.swipeRefreshGoodsDetail.isRefreshing) {
            mDatabind.swipeRefreshGoodsDetail.isRefreshing = false
        }
    }

    private var mAdapterCouponList: DetailCouponListAdapter? = null
    private val couponIds = ArrayList<Int>()
    private var couponCheckedList = ArrayList<GoodsDetailCouponListResponse.ListBean>()

    @SuppressLint("NotifyDataSetChanged")
    private fun showBottomCouponDialog(it: GoodsDetailCouponListResponse?) {
        mAdapterCouponList = DetailCouponListAdapter(arrayListOf(), detailResult.goodName)
        dialogBottomCoupon = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_coupon_list, null)
        val swipeRecyclerViewCoupon = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerViewCoupon)
        val ivCouponClose = dialogView.findViewById<AppCompatImageView>(R.id.ivCouponClose)
        val title = dialogView.findViewById<AppCompatTextView>(R.id.title)

        swipeRecyclerViewCoupon.init(LinearLayoutManager(context), mAdapterCouponList!!).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )
        ivCouponClose.setOnClickListener {
            dialogBottomCoupon.dismiss()
        }
        swipeRecyclerViewCoupon.adapter = mAdapterCouponList
        if (it != null) {
            if (!it.isEmpty()) {
                mAdapterCouponList!!.setList(it.list)
                mAdapterCouponList!!.notifyDataSetChanged()
                title.text = "领取优惠券"
            } else {
                title.text = "暂无可用优惠券"
            }
        }
        mAdapterCouponList!!.setOnBoxCheckedClickListener(object : DetailCouponListAdapter.OnCheckedClickListener {
            override fun onBoxCheckedListener(
                position: Int,
                list: List<GoodsDetailCouponListResponse.ListBean>,//选中后的list
                newList: List<GoodsDetailCouponListResponse.ListBean>
            ) {
                couponCheckedList.clear()
                couponCheckedList.addAll(list)
                mViewModel.getBuyNowCouponList(specId, buyCount)
                couponIds.clear()
                if (list.isNotEmpty()) {
                    list.forEachIndexed { _, listBean ->
                        couponIds.add(listBean.id)
                    }
                }
                var price = goodsTotalPrice
                if (newList.isNotEmpty()) {
                    newList.forEachIndexed { _, listBean ->
                        if (listBean.isChecked) {
                            price = Util.sub(price, Util.div(listBean.money, 100.00, 1)).toDouble()
                        }
                        if (!listBean.isChecked) {
                            listBean.isAllow = price >= Util.div(listBean.condition, 100.00, 1)
                            mAdapterCouponList!!.setList(newList)
                            mAdapterCouponList!!.notifyDataSetChanged()
                        }
                    }
                }
            }
        })

        dialogBottomCoupon.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialogBottomCoupon.setContentView(dialogView)
        dialogBottomCoupon.show()
    }

    @SuppressLint("SetTextI18n", "MissingInflatedId")
    private fun showBottomDialogAddCar(showType: Int) {
        dialogBottom = context?.let { BottomSheetDialog(it, R.style.BottomSheetDialog) }!!
        val dialogView: View = LayoutInflater.from(context).inflate(R.layout.bottom_sku_dialog, null)
        tvSkuSellingPrice = dialogView.findViewById(R.id.tv_sku_selling_price)
        tvSkuSellingPriceUnit = dialogView.findViewById(R.id.tv_sku_selling_price_unit)
        tvSkuInfo = dialogView.findViewById(R.id.tv_sku_info)
        buySkuNo = dialogView.findViewById(R.id.buy_sku_no)
        buySkuAdd = dialogView.findViewById(R.id.buy_sku_add)
        buySkuRe = dialogView.findViewById(R.id.buy_sku_re)
        btnSubmit = dialogView.findViewById(R.id.btn_submit)
        buySkuNoLl = dialogView.findViewById(R.id.buy_sku_no_ll)
        ibSkuClose = dialogView.findViewById(R.id.ib_sku_close)
        val tvGoodsName = dialogView.findViewById<TextView>(R.id.tv_goods_name)
        llCoupon = dialogView.findViewById(R.id.llCoupon)
        ivSkuLogo = dialogView.findViewById(R.id.iv_sku_logo)
        val marketShopMainSkuList = dialogView.findViewById<TagFlowLayout>(R.id.market_shop_main_sku_list)
        val llBottomHideView = dialogView.findViewById<LinearLayout>(R.id.llBottomHideView)
        llBottomHideView.isVisible = showType == 0
        if (::detailResult.isInitialized) {
            tvGoodsName.text = detailResult.goodName
            ImageLoaderManager.loadRoundImageOrEmpty(context, detailResult.goodImg, ivSkuLogo, 5, R.drawable.shop_product_def)
        } else {
            RxToast.showToast("商品详情数据获取失败")
        }
        if (checkPosition != -1) {
            if (::goodsSkuResult.isInitialized) {
                tvSkuSellingPrice.text = "¥ " + goodsSkuResult.list[checkPosition].salePrice.toString()
                tvSkuSellingPriceUnit.text = "库存:" + goodsSkuResult.list[checkPosition].inventory.toString()
                tvSkuInfo.text = getString(R.string.yixuan) + goodsSkuResult.list[checkPosition].specName
            }
        }

        setSkuAdapterData(marketShopMainSkuList, 1)
        if (checkPosition == -1) {
            onUnChecked()
        } else {
            (marketShopMainSkuList.adapter as TagAdapter<*>).setSelectedList(checkPosition)
        }
        ibSkuClose.setOnClickListener {
            if (::dialogBottom.isInitialized && dialogBottom.isShowing) {
                dialogBottom.dismiss()
            }
        }
        llCoupon.setOnClickListener {
            //获取立即购买的商品的总数量
            val buyTotal = buySkuNo.text.toString().toDouble()//购买数量
            //计算购买商品的总价格
            goodsTotalPrice = Util.mul(goodsUnitPrice, buyTotal).toDouble()
            showLoading(getString(R.string.loading))
            buyCount = buySkuNo.text.toString().toInt()
            mViewModel.getBuyNowCouponList(specId, buyCount)
        }
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    private fun setSkuAdapterData(marketShopMainSkuList: TagFlowLayout, type: Int) {//type：1底部弹出2详情页面
        val tagAdapter = object : TagAdapter<GoodsSkuResponse.ListBean>(skuList) {
            override fun getView(parent: FlowLayout?, position: Int, skuItemBean: GoodsSkuResponse.ListBean): View {
                val tv = layoutInflater.inflate(R.layout.sku_tv, parent, false) as TextView
                tv.text = skuItemBean.specName
                return tv
            }

            @SuppressLint("SetTextI18n")
            override fun onSelected(position: Int, view: View?) {
                super.onSelected(position, view)
                mDatabind.includeContent.includeContentTwo.tvProductSku.text = skuList[position].specName
                lowPriceSpecIndex = -1
                checkPosition = position
                if (::goodsSkuResult.isInitialized) {
                    specId = goodsSkuResult.list[position].id
                }
                if (type == 1) {
                    onChecked(skuList[position])
                    ImageLoaderManager.loadRoundImageOrEmpty(context, skuList[position].specImgPath, ivSkuLogo, 5, R.drawable.shop_product_def)
                } else {
                    ImageLoaderManager.loadRoundImageOrEmpty(
                        context,
                        skuList[position].specImgPath,
                        mDatabind.includeContent.ahImgTop,
                        5,
                        R.drawable.shop_product_def
                    )
                }
                setPrice(skuList[position].salePrice, skuList[position].showPrice)
            }

            override fun unSelected(position: Int, view: View?) {
                super.unSelected(position, view)
                checkPosition = -1
                if (type == 1) {
                    onUnChecked()
                } else {
                    if (::detailResult.isInitialized) {
                        setPrice(detailResult.salePrice, detailResult.showPrice)
                    } else {
                        RxToast.showToast("商品详情数据获取失败")
                    }
                }
            }
        }
        if (lowPriceSpecIndex == -1) {
            if (checkPosition != -1) {
                tagAdapter.setSelectedList(checkPosition)//默认选中的标签位置
                mDatabind.includeContent.includeContentTwo.tvProductSku.text = skuList[checkPosition].specName
            }
        } else {
            tagAdapter.setSelectedList(lowPriceSpecIndex)//默认选中的标签位置
            mDatabind.includeContent.includeContentTwo.tvProductSku.text = skuList[lowPriceSpecIndex].specName
        }
        marketShopMainSkuList.adapter = tagAdapter
    }

    private fun onUnChecked() {
        tvSkuSellingPrice.text = "¥0.0"
        tvSkuSellingPriceUnit.text = "库存:0"
        tvSkuInfo.text = getString(R.string.qingxuanze)
        context?.let { ContextCompat.getColor(it, R.color.color_8F8F8F) }?.let { btnSubmit.setBackgroundColor(it) }
        btnSubmit.text = getString(R.string.market_shop_product_detail_sku_activity_dialog_please_select_sku)
        buySkuNoLl.visibility = View.INVISIBLE
        btnSubmit.isClickable = false
        buySkuAdd.isClickable = false
        buySkuRe.isClickable = false
        if (buyType == 2) {
            llCoupon.visibility = View.GONE
        }
    }

    @SuppressLint("SetTextI18n")
    private fun onChecked(listBean: GoodsSkuResponse.ListBean) {
        goodsUnitPrice = listBean.salePrice
        tvSkuSellingPrice.text = "¥" + listBean.salePrice.toString()
        tvSkuSellingPriceUnit.text = "库存:" + listBean.inventory.toString()
        tvSkuInfo.text = getString(R.string.yixuan) + listBean.specName
        context?.let { ContextCompat.getColor(it, R.color.color_fe4542) }?.let { btnSubmit.setBackgroundColor(it) }
        if (buyType == 2) {
            btnSubmit.text = getString(R.string.market_shop_product_detail_sku_activity_dialog_purchase)
        } else if (buyType == 1) {
            btnSubmit.text = getString(R.string.market_shop_product_detail_sku_activity_dialog_add_shop_car)
        }
        if (buyType == 2) {
            llCoupon.visibility = View.VISIBLE
        }
        buySkuNoLl.visibility = View.VISIBLE
        btnSubmit.isClickable = true
        buySkuAdd.isClickable = true
        buySkuRe.isClickable = true
        if (buySkuNo.text.toString().toInt() > listBean.inventory) {
            buySkuNo.text = "" + listBean.inventory
        }
        buySkuAdd.setOnClickListener {
            val skuNoNow = buySkuNo.text.toString().toInt()
            if (skuNoNow < 2) {
                return@setOnClickListener
            } else {
                buySkuNo.text = "" + (skuNoNow - 1)
            }
            val finalPrice = Util.mul(goodsUnitPrice, buySkuNo.text.toString().toDouble()).toDouble()
            isCanUseCoupon(finalPrice)
        }
        buySkuRe.setOnClickListener {
            val skuNoNow = buySkuNo.text.toString().toInt()
            if (skuNoNow >= listBean.inventory) {
                RxToast.showToast("商品数量不可大于库存")
                return@setOnClickListener
            } else {
                buySkuNo.text = "" + (skuNoNow + 1)
            }
            val finalPrice = Util.mul(goodsUnitPrice, buySkuNo.text.toString().toDouble()).toDouble()
            isCanUseCoupon(finalPrice)
        }

        btnSubmit.setOnClickListener {
            //1加购物车 2直接购买
            buyCount = buySkuNo.text.toString().toInt()
            if (buyCount < 1) {
                RxToast.showToast(getString(R.string.MarketShopProductDetailSkuActivityDialogBuyCountLowerThanZero))
                return@setOnClickListener
            }
            if (buyType == 1) {//加入购物车
                showLoadingAntiShake(getString(R.string.loading))
                val body = AddShoppingCarParam(id.toInt(), specId, buyCount)
                mViewModel.addToShopCart(body)
            } else {//立即购买
                showLoadingAntiShake(getString(R.string.loading))
                val body = BuyNowParam(specId = specId, buyCount = buyCount, couponIds = couponIds, addrId = addressId)
                mViewModel.buyNow(body)
            }
        }
    }

    private fun isCanUseCoupon(finalPrice: Double) {
        val goodPrice = BigDecimal(finalPrice)
        if (couponCheckedList.isNotEmpty()) {
            couponCheckedList.forEachIndexed { _, listBean ->
                LogUtils.debugInfo(BigDecimal(Util.div(listBean.condition, 100.00, 2)).toString())
                if (goodPrice.compareTo(BigDecimal(Util.div(listBean.condition, 100.00, 2))) == -1) {//前者小于后者
                    RxToast.showToast("不符合优惠券使用条件，请重新选择优惠券")
                    couponIds.clear()
                }
            }
        }
    }

    private fun setProductSkuData(it: GoodsSkuResponse?) {
        if (it == null) {
            RxToast.showToast(getString(R.string.market_shop_product_detail_activity_get_sku_detail_err))
            return
        }
        if (it.list.size == 0) {
            RxToast.showToast(getString(R.string.market_shop_product_detail_activity_get_sku_detail_err))
            return
        }
        skuList = it.list

        setSkuAdapterData(mDatabind.includeContent.includeContentTwo.marketShopSkuList, 2)

        if (checkPosition != -1 && ((it.list.size - 1) >= checkPosition)) {
            (mDatabind.includeContent.includeContentTwo.marketShopSkuList.adapter as TagAdapter<*>).setSelectedList(checkPosition)
        }
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    private fun setProductData(it: GoodsDetailResponse) {
        initBanner(it.carousel)
        mDatabind.includeContent.includeContentOne.tvGoodsDetailFee.isVisible = it.firstWeightFee.toInt() != -1
        channelId = if (it.userId == 0) "" else it.userId.toString()
        mViewModel.chargeDiscribe.set(it.chargeDesc)
        lowPriceSpecIndex = it.lowPriceSpecIndex
        mDatabind.includeContent.includePriceInfo.tvProductDetailVisits.text = if (it.clickCnt > 999) "999+" else {
            it.clickCnt.toString()
        }

        mDatabind.data = it
        couponShopId = it.shopId
        isCollect = it.isCollect
        shopId = it.shopId
        if (isCollect) {
            mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_checked)
        } else {
            mDatabind.includeBottom.ivProductDetailCollect.setBackgroundResource(R.mipmap.icon_collect_unchecked)
        }
        if (!it.isEmptyDesc()) {
            mAdapter.setList(it.deses)
            mAdapter.notifyDataSetChanged()
        }
        if (it.imgDescriptions.isNotEmpty()) {
            mAdapterImage.setList(it.imgDescriptions)
            mAdapterImage.notifyDataSetChanged()
        }
        if (!it.isEmptyCouponList()) {
            mAdapterCoupon.setList(it.list)
            mAdapterCoupon.notifyDataSetChanged()
        }
        brandLogo = it.brandLogo
        ImageLoaderManager.loadRoundImageOrEmpty(context, it.goodImg, mDatabind.includeContent.ahImgTop, 5, R.drawable.shop_product_def)
        setPrice(it.salePrice, it.showPrice)
    }

    private fun initBanner(it: ArrayList<String>) {
        bannerImgList.clear()
        it.forEachIndexed { _, mImageUrl ->
            bannerImgList.add(mImageUrl)
        }
        mDatabind.includeContent.bannerGoodsDetail.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(bannerImgList), false)//设置banner的适配器,是否支持无限循环
            .setIndicator(CircleIndicator(context))
            .isAutoLoop(true)
            .setLoopTime(3000).setOnBannerListener { data, position ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast("图片资源获取失败")
                    return@setOnBannerListener
                }
                nav().navigateAction(R.id.action_to_fragment_big_image, Bundle().apply {
                    putStringArrayList("imageList", bannerImgList)
                    putInt("clickPosition", position)
                })
            }
        mDatabind.includeContent.bannerGoodsDetail.setBannerRound(20F)
    }


    @SuppressLint("SetTextI18n")
    private fun setPrice(salePrice: Double, showPrice: Double) {
        val isHide = !(salePrice == showPrice || showPrice == 0.0)
        mDatabind.includeContent.includePriceInfo.llDiscountsPrice.isVisible = isHide
        mDatabind.includeContent.includePriceInfo.tvPriceShow.text = showPrice.toString()
        val result = salePrice.toString().split(".")
        if (result.size > 1) {
            RxTextTool.getBuilder("")
                .append("¥")
                .append(result[0]).setBold().setAppearance(70).setTextColor(Color.WHITE)
                .append(".")
                .append(result[1])
                .into(mDatabind.includeContent.includePriceInfo.productItemPrice)
        }
    }
}